<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2022/1/17
 * Time: 17:58
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);

namespace app\api\controller;

use app\api\model\mysql\MallCart;
use app\api\model\mysql\MallCollect;
use app\api\model\mysql\MallGoods;
use app\api\model\mysql\MallGoodsSku;
use app\api\model\mysql\MallSpecs;
use app\api\model\mysql\MallSpecsValue;
use app\common\lib\Show;
use app\common\lib\Status;
use think\facade\Log;

class Goods extends Base
{





    /**
     * 搜索商品
     * @return \think\response\Json
     */
    public function getGoodsList(){
        $keyword =$this->request->param('keyword','','trim');
        $page =$this->request->param('page',1,'intval');
        $where =[];
        if($keyword){
            $where[]=[['title','like','%'.$keyword.'%']];
        }
        $where[]=[['status','=',1]];
        try {
            $lists = (new MallGoods())->field('id,title,logo,price')->where($where)->page($page,10)->select()->toArray();
        } catch (\Exception $e) {
            Log::error("goods_getTopTenByListInfo" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
            return Show::json_show(Status::mini_error, "查询错误");
        }
        return Show::json_show(Status::mini_normal, "ok", [
            'goods'=>$lists??[]
        ]);
    }

    /**
     * 按照销量排序
     * @return \think\response\Json
     */
    public function getTopTenByListInfo()
    {
        try {
            $lists = (new MallGoods())->getTopTenByList();
        } catch (\Exception $e) {
            Log::error("goods_getTopTenByListInfo" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
            return Show::json_show(Status::mini_error, "查询错误");
        }
        return Show::json_show(Status::mini_normal, "ok", $lists);
    }

    /**
     * 获取指定商品
     * @return \think\response\Json
     */
    public function getIsAppointByList()
    {
        try {
            $lists = (new MallGoods())->getIsAppointByList('id,title,logo,price,sku_id');
        } catch (\Exception $e) {
            Log::error("goods_getIsAppointByList" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
            return Show::json_show(Status::mini_error, "查询错误");
        }
        return Show::json_show(Status::mini_normal, "ok", $lists);
    }

    public function checkGoods(){
        $goods_id = $this->request->param('id', 0, 'intval');
        try {
            $goods = (new MallGoods())->getGoodsDetail($goods_id, 'id,cate_id,title,status');
        } catch (\Exception $e) {
            Log::error("goods_detail" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
            return Show::json_show(Status::mini_error, "查询错误");
        }
        if (!$goods) {
            return Show::json_show(Status::mini_error, "商品不存在");
        }
        return Show::json_show(Status::mini_normal, "ok", [
            'goods'=>$goods
        ]);
    }


    /**
     * 商品详情
     * @return \think\response\Json
     */
    public function getGoodsDetail()
    {
        $goods_id = $this->request->param('id', 0, 'intval');
        $openid = $this->request->param('openid', '', 'trim');
        try {
            $goods = (new MallGoods())->getGoodsDetail($goods_id, 'id,cate_id,cate_ids,title,describe,images,video,market_price,price,sales,thumb_title,sku_id,logo,stock,status');
        } catch (\Exception $e) {
            Log::error("goods_detail" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
            return Show::json_show(Status::mini_error, "查询错误");
        }
        if (!$goods) {
            return Show::json_show(Status::mini_error, "商品不存在");
        } else {
            $goods['describe'] = htmlspecialchars_decode($goods['describe']);
            $goodsimg = explode('|', $goods['images']);
            $goods_imgs = [];
            if(!empty($goods['video'])) {
                $goods_imgs[]['url'] = $goods['video'];
            }
            foreach ($goodsimg as $k => $v) {
                $m = $k + 1;
                $goods_imgs[]['url'] = $v;
            }
            $goods['images'] = $goods_imgs;
            // 判断用户是否收藏该商品
            try {
                $collect = (new MallCollect())->getMallCollectByOpenidAndGoodsInfo($openid, $goods_id);
            } catch (\Exception $e) {
                Log::error("goods_Collect" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
                return Show::json_show(Status::mini_error, "查询错误");
            }
            if (!$collect) {
                $goods['iscollect'] = 0;
            } else {
                $goods['iscollect'] = 1;
            }
            unset($goods['video']);
            //查询sku信息
            try {
                $sku = (new MallGoodsSku())->getMallGoodsSkuByValues($goods_id);
            } catch (\Exception $e) {
                Log::error("goods_Collect" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
                return Show::json_show(Status::mini_error, "查询错误");
            }
            if (!empty($sku)) {
                $skus = [];
                foreach ($sku as $value) {
                    if (empty($value['specs_value_ids'])) {
                        //单商品
                        $skus[] = [];
                    } else {
                        //多商品
                        $key = explode('-', $value['specs_value_ids']);
                        foreach ($key as $v) {
                            $skus[] = $v;
                        }
                    }
                }
                if (!empty($skus[0])) {
                    $specs = array_unique($skus);

                    try {
                        $specs_value_data = (new MallSpecsValue())->getSpecsValueByIds($specs);
                    } catch (\Exception $e) {
                        return Show::json_show(Status::mini_error, "sku信息错误");
                    }
                    $specs_ids = array_column($specs_value_data, "specs_id");
                    try {
                        $specs_data = (new MallSpecs())->getSpecsByValue($specs_ids);
                    } catch (\Exception $e) {
                        return Show::json_show(Status::mini_error, "sku信息错误");
                    }

                    $goods['skus'] = [
                        "specs_data" => $specs_data ?? [],
                        "specs_value_data" => $specs_value_data
                    ];
                } else {
                    $goods['skus'] = [];
                }
            } else {
                return Show::json_show(Status::mini_error, "商品sku不存在");
            }
        }
        if(in_array($goods['cate_ids'],[10,11,12,13,8,9])){
            $goods['isGift'] =1;
        }else{
            $goods['isGift'] =0;
        }


        return Show::json_show(Status::mini_normal, "ok", [
            'goods' => $goods
        ]);
    }

    /**
     * @return \think\response\Json
     */
    public function getGoodsSpecsByList()
    {
        $goods_id = $this->request->param('goods_id', 0, 'intval');
        $specs = $this->request->param('specs');

        $specs_value = "";
        if (empty($specs)) {
            return Show::json_show(Status::mini_error, "规格不存在");
        }
        $specs_id = array_column($specs, "id");
        $specs_value = implode('-', $specs_id);
        try {
            $skus = (new MallGoodsSku())->getMallGoodsSkuByList($goods_id, $specs_value);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, "查询失败");
        }
        if (!$skus) {
            return Show::json_show(Status::mini_normal, "ok");
        }
        $result = $skus->toArray();
        return Show::json_show(Status::mini_normal, 'ok', $result);
    }

    /**
     * 商品收藏与取消收藏接口
     * @return \think\response\Json
     */
    public function doGoodsCollect(){
        $goods_id = $this->request->param('goods_id', 0, 'intval');
        $openid = $this->request->param('openid', '', 'trim');
        try {
            $goods = (new MallGoods())->getGoodsDetail($goods_id, 'id,title');
        } catch (\Exception $e) {
            Log::error("goods_detail" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
            return Show::json_show(Status::mini_error, "查询错误");
        }
        if (!$goods) {
            return Show::json_show(Status::mini_error, "商品不存在");
        }

        // 判断用户是否收藏该商品
        try {
            $collect = (new MallCollect())->getMallCollectByOpenidAndGoodsInfo($openid, $goods_id);
        } catch (\Exception $e) {
            Log::error("goods_Collect" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
            return Show::json_show(Status::mini_error, "查询错误");
        }

        if($collect){
            (new MallCollect())->where("id='".$collect['id']."'")->delete();
        }else{
            $data=array(
                'openid'=>$openid,
                'goods_id'=>$goods_id
            );
            try {
                (new MallCollect())->save($data);
            } catch (\Exception $e) {
                Log::error("goods_doCollect" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
                return Show::json_show(Status::mini_error, "操作失败");
            }
        }
        return Show::json_show(Status::mini_normal, 'ok',[]);
    }

    /**
     * 加入购物车
     * @return \think\response\Json
     */
    public function addToCart(){
        $goods_id   = $this->request->param('goods_id', 0, 'intval');
        $openid     = $this->request->param('openid', '', 'trim');
        $buynum     = $this->request->param('buynum', 1, 'intval');
        $option_id  = $this->request->param('option_id',0,'intval');  // 规格id

        try {
            $goods = (new MallGoods())->getGoodsDetail($goods_id, 'id,cate_id,title,describe,images,video,price,sales,thumb_title,sku_id,logo,stock');
        } catch (\Exception $e) {
            Log::error("goods_detail" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
            return Show::json_show(Status::mini_error, "查询错误");
        }
        if (!$goods) {
            return Show::json_show(Status::mini_error, "商品不存在");
        }

        if(in_array($goods['cate_id'],[10,11,12,13])){
            return Show::json_show(Status::mini_error, "该商品不支持加入购物车，请选择立即购买");
        }

        if($option_id>0){
            try {
                $skus = (new MallGoodsSku())->getGoodsSkuById($goods_id, $option_id);
            } catch (\Exception $e) {
                Log::error("goods_detail" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
                return Show::json_show(Status::mini_error, "查询失败");
            }
            if(!$skus){

                return Show::json_show(Status::mini_error, "商品规格不存在");
            }
            if($skus['stock']<$buynum){

                return Show::json_show(Status::mini_error, "商品库存不足");
            }
        }
        $cartmodel =(new MallCart());
        try {
            $cartinfo = $cartmodel->getCartByGoodsId($goods_id,$option_id,$openid);
        } catch (\Exception $e) {
            Log::error("goods_detail" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
            return Show::json_show(Status::mini_error, "查询失败");
        }
        $data=array(
            'goods_id'    =>$goods_id,
            'option_id'   =>$option_id,
            'option_name' =>$skus['specs_value_ids'],
            'is_dan'      =>$skus['is_dan'],
            'goods_price' =>$skus['price'],
            'market_price'=>$skus['market_price'],
            'image'    =>$skus['image'],
            'goods_name' =>$goods['title'],
            'thumb_title' =>$goods['thumb_title'],
            'total'       =>$buynum,
            'openid'      =>$openid
        );
        try{
            if($cartinfo){
                $cartinfo->save(array('total'=>$cartinfo['total']+$buynum));
            }else{
                $cartmodel->save($data);
            }
        }catch ( \Exception $e){
            return Show::json_show(Status::mini_error, "查询错误");
        }

        return Show::json_show(Status::mini_normal, 'ok', []);
    }



}